<script setup>
  import {
    forecastHours,
    forecast,
    forecastNow
  } from './api.js'
  import futureWeather from './components/FutureWeather/index.vue'
  import {
    ref,
    reactive,
    onMounted,
    getCurrentInstance,
    nextTick
  } from 'vue'
  import {
    onLoad,
    onPageScroll,
    onPullDownRefresh,
  } from '@dcloudio/uni-app'
  const {
    proxy
  } = getCurrentInstance()
  const forecastHoursList = ref([])
  const forecastList = ref([])
  const isScorll = ref(false)
  const swiperHeight = ref(980)
  const searchCity = ref({})
  const today = ref({})
  const currentTemperature = ref('')
  const tempMaxList = ref([])
  const tempMinList = ref([])
  const localArea = ref([])
  const cityDate = ref({})
  const cityLocation = ref([])
  const currentId = ref(0)
  const currentLocation = ref({})
  onLoad(async (e) => {
    cityLocation.value = uni.getStorageSync('cityCache') || []
    console.log(cityLocation.value.length, 122)
    if (!cityLocation.value || cityLocation.value.length < 1) {
      uni.reLaunch({
        url: '/pages/city/city-search'
      })
      return
    }
    if (e && e.cityList) {
      currentId.value = cityLocation.value.findIndex(item => item.adcode == JSON.parse(e.cityList).adcode)
    } else {
      if (uni.getStorageSync('currentLocation')) {
        currentLocation.value = JSON.parse(uni.getStorageSync('currentLocation')) || {}
        currentId.value = cityLocation.value.findIndex(item => item.adcode == currentLocation.value.adcode)
      }
    }
    cityDate.value = cityLocation.value[currentId.value]
    PromiseAll(cityLocation.value)
  })

  function querySelect() {
    const query = uni.createSelectorQuery().in(this);
    query.select(`#content-0`).boundingClientRect(res => {
      if (res) {
        swiperHeight.value = res.height;
      }
    }).exec()
  }
  onPageScroll((e) => {
    if (e.scrollTop > 1) {
      isScorll.value = true
    } else {
      isScorll.value = false
    }
  })
  //实时天气
  const realTime = ref({})
  const forecastNowApi = (async (adcode, location, id) => {
    const res = await forecastNow({
      adcode: adcode,
      id: id,
      location: location
    })
    if (res && res.code == 1) {
      realTime.value = res.data
      return res.data
    }
  })
  //24小时天气
  const skycon = ref([])
  const weatherTip = ref('')
  const forecastHoursApi = (async (adcode, location, id) => {
    const res = await forecastHours({
      adcode: adcode,
      id: id,
      location: location
    })
    if (res && res.code == 1) {
      forecastHoursList.value = res.data
      currentTemperature.value = res.data[0].temp
      forecastHoursList.value.forEach(e => {
        e.fxTime = e.fxTime.split('T')[1].split('+')[0]
        e.iconImg = proxy.$getWeatherImage(e.icon)
      })
      return {
        forecastHoursList: forecastHoursList.value,
        currentTemperature: currentTemperature.value
      }

    } else {
      uni.showToast({
        title: res.msg,
        icon: 'none'
      })
    }
  })
  //15天天气
  const AirQuality = ref('')
  const AirQualityValue = ref('')
  const weatherAll = ref({})
  const forecastApi = (async (adcode, location, id) => {
    const res = await forecast({
      adcode: adcode,
      id: id,
      location: location
    })
    if (res && res.code == 1) {
      today.value = res.data[0]
      forecastList.value = res.data
      forecastList.value.forEach((e) => {
        e.weekstate = proxy.$checkDateRelativeToToday(e.fxDate)
        e.textDayImg = proxy.$getWeatherImage(e.iconDay)
        e.textNightImg = proxy.$getWeatherImage(e.iconNight)
        e.week = proxy.$weekdate(e.fxDate)
        e.airQuality = proxy.$getAirQualitySimple(e.aqi)
        let date = new Date(e.fxDate);
        let month = date.getMonth() + 1
        let day = date.getDate();
        e.fxDate = `${month}月${day}日`
      })
      AirQuality.value = proxy.$getAirQuality(res.data[0].aqi)
      AirQualityValue.value = res.data[0].aqi
      tempMaxList.value = res.data.map(e => {
        return +e.tempMax
      })
      tempMinList.value = res.data.map(e => {
        return +e.tempMin
      })
      querySelect()
      return {
        today: today.value,
        forecastList: forecastList.value,
        AirQuality: AirQuality.value,
        AirQualityValue: AirQualityValue.value,
        tempMaxList: tempMaxList.value,
        tempMinList: tempMinList.value
      }
    }
  })

  function PromiseAll(array) {
    array.forEach((e, index) => {
      const weatherNow = forecastNowApi(e.adcode)
      const weatherHours = forecastHoursApi(e.adcode)
      const weatherforecast = forecastApi(e.adcode)

      Promise.all([weatherNow, weatherHours, weatherforecast]).then((results) => {
        e.realTime = results[0]
        e.currentTemperature = results[1].currentTemperature
        e.forecastHoursList = results[1].forecastHoursList
        e.today = results[2].today
        e.forecastList = results[2].forecastList
        e.AirQuality = results[2].AirQuality
        e.AirQualityValue = results[2].AirQualityValue
        e.tempMaxList = results[2].tempMaxList
        e.tempMinList = results[2].tempMinList
        uni.setStorageSync('cityCache', array)
      }).catch((err) => {
        console.log(err, 999)
      })
    })
  }

  function selectCity() {
    uni.navigateTo({
      url: '/pages/city/city-select'
    })
  }

  function addCity() {
    uni.navigateTo({
      url: '/pages/city/city-search'
    })
  }

  function handleTouchStart(e) {
    e.stopPropagation();
  }

  function handleTouchMove(e) {
    e.stopPropagation();
  }

  function onSwiperChange(e) {
    cityDate.value = cityLocation.value[e.detail.current]
    const current = e.detail.current
    updateHeight(current)
    const weatherNow = forecastNowApi(cityDate.value.adcode)
    const weatherHours = forecastHoursApi(cityDate.value.adcode)
    Promise.all([weatherNow, weatherHours]).then((results) => {
      cityDate.value.realTime = results[0]
      cityDate.value.currentTemperature = results[1].currentTemperature
      cityDate.value.forecastHoursList = results[1].forecastHoursList
    }).catch((err) => {
      console.log(err, 999)
    })
  }

  function updateHeight(index) {
    const query = uni.createSelectorQuery().in(this);
    query.select(`#content-${index}`).boundingClientRect(res => {
      if (res) {
        swiperHeight.value = res.height;
      }
    }).exec();
  }

  onPullDownRefresh(async () => {
    const weatherNow = forecastNowApi(cityDate.value.adcode)
    const weatherHours = forecastHoursApi(cityDate.value.adcode)
    const weatherforecast = forecastApi(cityDate.value.adcode)
    await Promise.all([weatherNow, weatherHours, weatherforecast]).then((results) => {
      cityDate.value.realTime = results[0]
      cityDate.value.currentTemperature = results[1].currentTemperature
      cityDate.value.forecastHoursList = results[1].forecastHoursList
      cityDate.value.today = results[2].today
      cityDate.value.forecastList = results[2].forecastList
      cityDate.value.AirQuality = results[2].AirQuality
      cityDate.value.AirQualityValue = results[2].AirQualityValue
      cityDate.value.tempMaxList = results[2].tempMaxList
      cityDate.value.tempMinList = results[2].tempMinList
    }).catch((err) => {
      console.log(err, 999)
    })
    await uni.stopPullDownRefresh();
  })
</script>

<template>
  <view class="home-page" :class="$getWeatherBackground(cityDate.realTime.icon)">
    <view class="home-bg"
      :style="'background:url('+$getWeatherHomeImage(cityDate.realTime.icon) +') no-repeat;background-size: contain;'">
    </view>
    <view :class="['home-header', { scrolled: isScorll }]"
      :style="{ backgroundColor: isScorll? $getWeatherHeaderBackground(cityDate.realTime.icon) :''}">
      <view class="header-plus" @click="addCity"><up-icon name="plus" color="#fff" size="48rpx"></up-icon></view>
      <view class="header-content">{{cityDate.location_name?cityDate.location_name:cityDate.district}}
        {{cityDate.adm2_name?cityDate.adm2_name:cityDate.city}}
      </view>
      <view class="header-more" @click="selectCity"><up-icon name="more-dot-fill" color="#fff" size="48rpx"></up-icon>
      </view>
    </view>
    <view class="container">
      <template v-if="cityLocation.length >1 &&currentId>-1">
        <swiper class="swiper" :indicator-dots="cityLocation.length >1 ?true :false"
          indicator-color="rgba(255, 255, 255, 0.5)" :current="currentId"
          indicator-active-color="rgba(255, 255, 255, 1)" :style="{ height: swiperHeight + 'px' }"
          @change="onSwiperChange">
          <swiper-item v-for="item,index in cityLocation" :key="index">
            <view class="content" :id="'content-' + index">
              <view class="home-nav">
                <view class="nav-temperature">
                  <view class="">{{item.realTime.temp}}</view>
                  <view class="">°</view>
                </view>
                <view class="weather-temperature">
                  <view class="weather">{{item.realTime?item.realTime.text:''}}
                  </view>
                  <view class="temperature">
                    {{item.today?item.today.tempMax:''}}°/{{item.today?item.today.tempMin:''}}°
                  </view>
                </view>
                <view class="nav-condition">
                  <view class="condition-content" v-if="item.AirQuality">
                    <image src="@/static/icon/leaf.png" mode=""></image>
                    <view class="">{{item.AirQuality}} {{item.AirQualityValue}}</view>
                  </view>
                  <view class="condition-content" v-if="item.weatherTip">
                    <image src="@/static/icon/water-line.png" mode=""></image>
                    <view class="">{{item.weatherTip}}</view>
                  </view>
                </view>
              </view>
              <view class="forecast-daily">
                <view class="forecast-title">24小时预报</view>
                <scroll-view class="forecast-content" scroll-x="true" @touchstart="handleTouchStart"
                  @touchmove="handleTouchMove">
                  <view class="forecast-nav" :class="ind== 0? 'forecast-active':''"
                    v-for="ele,ind in item.forecastHoursList" :key="ind">
                    <view class="forecast-time">{{ele.fxTime}}</view>
                    <view class="forecast-icon">
                      <image :src="ele.iconImg" mode=""></image>
                    </view>
                    <view class="forecast-weather">{{ele.text}}</view>
                  </view>
                </scroll-view>
              </view>
              <view class="weather-future">
                <view class="future-title">15天预报</view>
                <futureWeather :listData="item.forecastList" :tempMaxList="item.tempMaxList"
                  :tempMinList="item.tempMinList">
                </futureWeather>
              </view>
            </view>
          </swiper-item>
        </swiper>
      </template>
      <template v-else>
        <view class="content">
          <view class="home-nav">
            <view class="nav-temperature">
              <view class="">{{realTime.temp}}</view>
              <view class="">°</view>
            </view>
            <view class="weather-temperature">
              <view class="weather">{{realTime.text}}</view>
              <view class="temperature">
                {{today.tempMax}}°/{{today.tempMin}}°
              </view>
            </view>
            <view class="nav-condition">
              <view class="condition-content" v-if="AirQuality">
                <image src="@/static/icon/leaf.png" mode=""></image>
                <view class="">{{AirQuality}} {{AirQualityValue}}</view>
              </view>
              <view class="condition-content" v-if="weatherTip">
                <image src="@/static/icon/water-line.png" mode=""></image>
                <view class="">{{weatherTip}}</view>
              </view>
            </view>
          </view>
          <view class="forecast-daily">
            <view class="forecast-title">24小时预报</view>
            <scroll-view class="forecast-content" scroll-x="true" @touchstart="handleTouchStart"
              @touchmove="handleTouchMove">
              <view class="forecast-nav" :class="index== 0? 'forecast-active':''"
                v-for="item,index in forecastHoursList" :key="index">
                <view class="forecast-time">{{item.fxTime}}</view>
                <view class="forecast-icon">
                  <image :src="item.iconImg" mode=""></image>
                </view>
                <view class="forecast-weather">{{item.text}}</view>
              </view>
            </scroll-view>
          </view>
          <view class="weather-future">
            <view class="future-title">15天预报</view>
            <futureWeather :listData="forecastList" :tempMaxList="tempMaxList" :tempMinList="tempMinList">
            </futureWeather>
          </view>
        </view>
      </template>
    </view>
  </view>
</template>

<style lang="scss">
  $fine-color: rgba(141, 173, 252, 1), rgba(48, 94, 209, 1), rgba(19, 61, 168, 1);
  $fine-img: '/static/image/fine.png';

  // 定义天气主题映射
  $weather-themes: (
    'sunny': (color1: rgba(141, 173, 252, 1),
      color2: rgba(48, 94, 209, 1),
      color3: rgba(19, 61, 168, 1),
      image: '/static/image/fine.png'
    ),
    'cloudy': (color1: rgba(141, 173, 252, 1),
      color2: rgba(48, 94, 209, 1),
      color3: rgba(19, 61, 168, 1),
      image: '/static/image/fine.png'
    ),
    'rainy': (color1: rgba(141, 173, 252, 1),
      color2: rgba(48, 94, 209, 1),
      color3: rgba(19, 61, 168, 1),
      image: '/static/image/fine.png'
    ),
    'snowy': (color1: rgba(141, 173, 252, 1),
      color2: rgba(48, 94, 209, 1),
      color3: rgba(19, 61, 168, 1),
      image: '/static/image/fine.png'
    ),
    'stormy': (color1: rgba(141, 173, 252, 1),
      color2: rgba(48, 94, 209, 1),
      color3: rgba(19, 61, 168, 1),
      image: '/static/image/fine.png'
    )
  );

  ::v-deep .uni-swiper-dots-horizontal {
    top: 0;
  }

  //晴
  .sunny {
    background: linear-gradient(133.41deg, #8DADFC 0%, #305ED1 63.36%, #133DA8 100%);
  }

  //雨天
  .rainstorm {
    background: linear-gradient(133.41deg, #B5B5B5 0%, #808287 62.8%, #444547 100%);
  }

  //多云
  .cloudy {
    background: linear-gradient(133.41deg, #919CB8 0%, #4E6396 69.3%, #2B3A5E 100%);
  }

  //阴天
  .clear {
    background: linear-gradient(133.41deg, #919CB8 0%, #4E6396 69.3%, #2B3A5E 100%);
  }

  //雾天
  .fog {
    background: linear-gradient(133.41deg, #8DADFC 0%, #305ED1 62.8%, #133DA8 100%);
  }

  //雪天
  .sleet {
    background: linear-gradient(133.41deg, #B5B5B5 0%, #808287 62.8%, #444547 100%);
  }

  //雾霾
  .smog {
    background: linear-gradient(133.41deg, #8F8F8F 0%, #656A75 63.36%, #272D38 100%);
  }

  //沙尘
  .sand-dust {
    background: linear-gradient(133.41deg, #DEB7A0 0%, #6B4A37 63.92%, #423529 100%);
  }

  .home-page {
    display: flex;
    flex-direction: column;
    align-items: center;
    overflow-y: scroll;

    .home-bg {
      width: 100%;
      height: 680rpx;
      mix-blend-mode: screen;
      opacity: 1;
      background: url() no-repeat;
      position: absolute;
      top: 0;
      background-size: contain;
      flex-shrink: 0;
    }

    @keyframes navbarAnimation {
      0% {
        opacity: 0;
      }

      100% {
        opacity: 1;
      }
    }

    .scrolled {
      // animation: navbarAnimation 0.5s ease-out forwards;
    }

    .home-header {
      width: 100%;
      height: 88rpx;
      display: flex;
      align-items: center;
      box-sizing: border-box;
      padding: 0 32rpx;
      flex-shrink: 0;
      position: fixed;
      top: 0;
      transition: background-color 0.3s ease, box-shadow 0.3s ease, transform 0.3s ease;
      z-index: 1;

      .header-content {
        flex: 1;
        text-align: center;
        font-size: 34rpx;
        font-weight: 500;
        color: rgba(255, 255, 255, 1);

      }
    }

    .container {
      flex: 1;
      width: 100%;
      margin-top: 88rpx;
    }

    .content {
      display: flex;
      flex-direction: column;
      align-items: center;
    }

    .home-nav {
      width: 100%;
      height: 504rpx;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      flex-shrink: 0;

      .nav-temperature {
        font-size: 144rpx;
        font-weight: 500;
        color: rgba(255, 255, 255, 1);
        display: flex;

        :last-child {
          font-size: 112rpx;
        }
      }

      .weather-temperature {
        font-size: 34rpx;
        font-weight: 500;
        color: rgba(255, 255, 255, 1);
        display: flex;
        align-items: center;

        .temperature {
          margin-left: 16rpx;
        }
      }

      .nav-condition {
        display: flex;
        margin-top: 32rpx;

        .condition-content {
          height: 48rpx;
          border-radius: 326rpx;
          background: rgba(255, 255, 255, 0.2);
          display: flex;
          justify-content: center;
          align-items: center;
          padding: 4rpx 20rpx 4rpx 20rpx;
          box-sizing: border-box;
          margin-left: 24rpx;
          font-size: 28rpx;
          font-weight: 400;
          color: rgba(255, 255, 255, 1);

          image {
            height: 28rpx;
            width: 28rpx;
          }
        }

      }
    }

    .forecast-daily {
      width: 91.5vw;
      height: 280rpx;
      border-radius: 24rpx;
      background: rgba(255, 255, 255, 0.2);
      margin-top: 32rpx;
      display: flex;
      flex-direction: column;
      box-sizing: border-box;
      padding: 24rpx 32rpx;
      flex-shrink: 0;

      .forecast-title {
        font-size: 34rpx;
        font-weight: 500;
        color: rgba(255, 255, 255, 1);

      }

      .forecast-content {
        flex: 1;
        overflow-x: scroll;
        font-size: 28rpx;
        font-weight: 500;
        color: rgba(255, 255, 255, 0.6);
        margin: 23rpx 0 0 10rpx;
        display: flex;
        align-items: center;

        ::v-deep .uni-scroll-view-content {
          display: flex;
          align-items: center;
        }

        :first-child {
          margin-left: 0 !important;
        }

        :last-child {
          margin-right: 0 !important;
        }

        .forecast-active {
          color: rgba(255, 255, 255, 1);
        }

        .forecast-nav {
          display: flex;
          flex-direction: column;
          height: 160rpx;
          align-items: center;
          flex-shrink: 0;
          margin: 0 31rpx;

          .forecast-icon {
            height: 64rpx;
            width: 64rpx;
            margin: 12rpx 0 8rpx;

            image {
              height: 64rpx;
              width: 64rpx;
            }
          }
        }
      }
    }

    .weather-future {
      width: 91.5vw;
      border-radius: 24rpx;
      background: rgba(255, 255, 255, 0.2);
      margin: 32rpx 0 42rpx 0;
      flex-shrink: 0;
      display: flex;
      flex-direction: column;
      box-sizing: border-box;
      padding: 24rpx 0 32rpx;

      .future-title {
        font-size: 34rpx;
        font-weight: 500;
        color: rgba(255, 255, 255, 1);
        padding-left: 32rpx;
      }


    }
  }
</style>